/*
 * @: diapatch 重新派发 有可能派发的还是promise
 * next 下一步 改状态了 
 * @Version: 1.0
 * @Autor: ziwei
 * @Date: 2021-11-01 10:41:02
 * @LastEditors: ziwei
 * @LastEditTime: 2021-11-01 11:55:22
 */
function promise({getState,dispatch}) {
  return function(next) {//调用下一个中间件 next=store，原始的dispatch方法
    return function(action) {//这个就是改造后的dispatch
      if(action.then && typeof action.then === 'function'){
        //action => dispatch(action) 不管成功失败都进行派发
        action.then(dispatch).catch(dispatch)
      }else if(action.payload && action.payload.then === 'function'){
        action.payload.then(payload=>dispatch({...action,payload})).catch(error=>{
          dispatch({...action,error:true,payload:error})
          return Promise.reject(error)
        });
      }else{
        next(action)
      }
    }
  }
}

export default promise